<template>
  <view class="task-overview">
    <!-- 顶部欢迎区域 -->
    <view class="welcome-section">
      <view class="greeting-info">
        <text class="greeting">{{ greeting }}，{{ userName }}</text>
        <text class="date">{{ currentDate }}</text>
        <text class="task-count">您有{{ pendingTasks }}个待提交任务</text>
      </view>
    </view>

    <!-- 验收任务列表 -->
    <view class="task-list-section">
      <view class="section-header">
        <text class="section-title">验收任务</text>
        <view class="status-tabs">
          <text 
            v-for="(tab, index) in statusTabs" 
            :key="index"
            class="status-tab"
            :class="{ active: activeTabIndex === index }"
            @click="switchTab(index)"
          >
            {{ tab.name }}
          </text>
        </view>
      </view>
      
      <view class="task-list">
        <view 
          v-for="task in filteredTasks" 
          :key="task.task_id" 
          class="task-item"
          @click="viewTaskDetail(task)"
        >
          <view class="task-content">
            <text class="task-title">{{ task.task_name }}</text>
            <text class="task-desc">{{ task.task_des }}</text>
            <view class="task-meta">
              <text class="task-date">📅 {{ formatDate(task.create_time) }}</text>
              <text class="task-author">👤 {{ task.create_user}}</text>
            </view>
          </view>
          <view class="task-status" :class="task.status">
            {{ getStatusText(task.status) }}
          </view>
        </view>
      </view>
    </view>

    <!-- 浮动新建按钮 -->
    <view class="fab" @click="showCreateModal">
      <text class="fab-icon">+</text>
    </view>

    <!-- 创建任务模态框 -->
    <view v-if="showModal" class="modal-overlay" @click="hideCreateModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">创建验收任务</text>
          <text class="modal-close" @click="hideCreateModal">×</text>
        </view>
        
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">任务名称</text>
            <input 
              class="form-input" 
              v-model="newTask.name" 
              placeholder="请输入任务名称"
            />
          </view>
          
          <view class="form-item">
            <text class="form-label">任务描述</text>
            <textarea 
              class="form-textarea" 
              v-model="newTask.description" 
              placeholder="请输入任务描述"
            />
          </view>
        </view>
        
        <view class="modal-footer">
          <button class="btn-cancel" @click="hideCreateModal">取消</button>
          <button class="btn-create" @click="createTask" :disabled="isCreating">
            {{ isCreating ? '创建中...' : '创建任务' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 响应式数据
const userName = ref('张经理')
const currentDate = ref('')
const showModal = ref(false)
const activeTabIndex = ref(0)
const isCreating = ref(false)

const statusTabs = [
  { name: '全部', filter: 'all' },
  { name: '进行中', filter: 'pending' },
  { name: '已完成', filter: 'completed' }
]

const token = uni.getStorageSync("userInfo").token;

const newTask = ref({
  name: '',
  description: ''
})

const recentTasks = ref([])
const modifiedTasks = ref(new Set()) // 记录已修改的任务ID

// 计算属性
const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 12) return '早上好'
  if (hour < 18) return '下午好'
  return '晚上好'
})

const totalTasks = computed(() => recentTasks.value.length)
const completedTasks = computed(() => recentTasks.value.filter(task => task.status === 'completed').length)
const pendingTasks = computed(() => recentTasks.value.filter(task => task.status === 'pending').length)

const filteredTasks = computed(() => {
  const filter = statusTabs[activeTabIndex.value].filter
  if (filter === 'all') {
    return recentTasks.value
  }
  return recentTasks.value.filter(task => task.status === filter)
})

// 生命周期
onMounted(() => {
  initPage()
  setStatusBarHeight()
})

// 方法
const initPage = () => {
  currentDate.value = formatCurrentDate()
  loadUserInfo()
  loadRecentTasks()
}

const formatCurrentDate = () => {
  const now = new Date()
  return `今天是${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日 ${getWeekDay(now.getDay())}`
}

const getWeekDay = (day) => {
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return weekDays[day]
}

const loadUserInfo = () => {
  const userInfo = uni.getStorageSync('userInfo')
  if (userInfo && userInfo.name) {
    userName.value = userInfo.name
  }
}

const loadRecentTasks = async () => {
  try {
    const response = await uni.request({
      url: './api/acc_task',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (response.statusCode === 200) {
      recentTasks.value = response.data || []
      console.log(response.data)
    } else {
      uni.showToast({
        title: '获取任务列表失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}

const setStatusBarHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  const statusBarHeight = systemInfo.statusBarHeight || 0
  // 在uni-app中，可以通过其他方式处理状态栏高度
  // 这里暂时注释掉document的使用
  // document.documentElement.style.setProperty('--status-bar-height', statusBarHeight + 'px')
}

const switchTab = (index) => {
  activeTabIndex.value = index
}

const showCreateModal = () => {
  showModal.value = true
}

const hideCreateModal = () => {
  showModal.value = false
  resetForm()
}

const resetForm = () => {
  newTask.value = {
    name: '',
    description: ''
  }
}

const createTask = async () => {
  if (!newTask.value.name.trim()) {
    uni.showToast({
      title: '请输入任务名称',
      icon: 'none'
    })
    return
  }
  
  isCreating.value = true
  
  try {
    const taskData = {
      task_name: newTask.value.name,
      task_des: newTask.value.description,
    }
    
    const response = await uni.request({
      url: './api/acc_task',
      method: 'POST',
      data: taskData,
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    
    if (response.statusCode === 200 || response.statusCode === 201) {
      hideCreateModal()
      loadRecentTasks() // 重新获取任务列表
      
      uni.showToast({
        title: '任务创建成功',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: '创建任务失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('创建任务失败:', error)
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
  } finally {
    isCreating.value = false
  }
}

const viewTaskDetail = (task) => {
  console.log("=== TaskOverview viewTaskDetail ===")
  console.log("task对象:", task)
  console.log("task.task_id:", task.task_id)
  
  // 使用正确的字段名task_id
  const taskId = task.task_id
  console.log("获取到的taskId:", taskId)
  
  if (!taskId) {
    uni.showToast({
      title: '任务ID无效',
      icon: 'none'
    })
    return
  }
  
  // 根据任务状态跳转到不同页面
  if (task.status === 'completed') {
    // 已完成任务跳转到历史记录页面
    console.log("跳转到历史记录页面:", `/pages/taskHistory/index?task_id=${taskId}`)
    uni.navigateTo({
      url: `/pages/taskHistory/index?task_id=${taskId}`
    })
  } else {
    // 其他状态任务跳转到原页面
    console.log("跳转到任务详情页面:", `/pages/index/index?task_id=${taskId}`)
    uni.navigateTo({
      url: `/pages/index/index?task_id=${taskId}`
    })
  }
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '进行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}
</script>

<style scoped>
.task-overview {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 120rpx;
}

/* 顶部欢迎区域 */
.welcome-section {
  background: white;
  padding: 60rpx 40rpx 80rpx;
  padding-top: calc(60rpx + var(--status-bar-height));
  color: #333;
  position: relative;
  overflow: hidden;
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.welcome-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><circle cx="20" cy="20" r="2" fill="rgba(255,255,255,0.1)"/><circle cx="80" cy="40" r="1.5" fill="rgba(255,255,255,0.1)"/><circle cx="40" cy="80" r="1" fill="rgba(255,255,255,0.1)"/></svg>');
  pointer-events: none;
}

.greeting-info {
  width: 100%;
  position: relative;
  z-index: 1;
}

.greeting {
  font-size: 48rpx;
  font-weight: 700;
  margin-bottom: 15rpx;
  display: block;
  color: #333;
}

.date {
  font-size: 30rpx;
  opacity: 0.7;
  margin-bottom: 15rpx;
  display: block;
  font-weight: 300;
  color: #666;
}

.task-count {
  font-size: 32rpx;
  display: block;
  background: #f0f4ff;
  color: #3498ff;
  padding: 15rpx 25rpx;
  border-radius: 50rpx;
  display: inline-block;
  border: 1rpx solid #e0e8ff;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(8rpx);
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { 
    transform: translateY(100rpx);
    opacity: 0;
  }
  to { 
    transform: translateY(0);
    opacity: 1;
  }
}

.modal-content {
  background: white;
  border-radius: 30rpx;
  width: 90%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow: hidden;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
  animation: slideUp 0.4s ease-out;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 50rpx 40rpx 30rpx;
  background: linear-gradient(135deg, #3498ff 0%, #3498ff 100%);
  color: white;
}

.modal-title {
  font-size: 38rpx;
  font-weight: 700;
  color: white;
}

.modal-close {
  font-size: 50rpx;
  color: rgba(255, 255, 255, 0.8);
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.modal-close:active {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(0.9);
}

.modal-body {
  padding: 50rpx 40rpx;
  background: #fafbfc;
}

.form-item {
  margin-bottom: 40rpx;
}

.form-label {
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
  font-weight: 600;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 30rpx 25rpx;
  border: 3rpx solid #e8ecf0;
  border-radius: 16rpx;
  font-size: 30rpx;
  color: #333;
  background: white;
  box-sizing: border-box;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.form-input:focus, .form-textarea:focus {
  border-color: #3498ff;
  box-shadow: 0 0 0 6rpx rgba(102, 126, 234, 0.1);
  transform: translateY(-2rpx);
} 

.form-input {
  height: 100rpx;
}

.form-textarea {
  height: 160rpx;
  resize: none;
  font-family: inherit;
}

.modal-footer {
  display: flex;
  gap: 25rpx;
  padding: 30rpx 40rpx 50rpx;
  background: white;
}

.btn-cancel {
  flex: 1;
  padding: 32rpx;
  background: #f8f9fa;
  color: #6c757d;
  border: 2rpx solid #e9ecef;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  transition: all 0.3s ease;
}

.btn-cancel:active {
  background: #e9ecef;
  transform: scale(0.98);
}

.btn-create {
  flex: 1;
  padding: 32rpx;
  background: linear-gradient(135deg, #3498ff 0%, #3498ff 100%);
  color: white;
  border: none;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  box-shadow: 0 8rpx 25rpx rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
}

.btn-create:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 15rpx rgba(102, 126, 234, 0.4);
}

/* 任务列表区域 */
.task-list-section {
  margin: 20rpx;
  background: white;
  border-radius: 20rpx;
  padding: 40rpx 30rpx 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 1;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 40rpx;
  font-weight: 700;
  color: #2c3e50;
  position: relative;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -8rpx;
  left: 0;
  width: 60rpx;
  height: 6rpx;
  background: linear-gradient(135deg, #3498ff 0%, #764ba2 100%);
  border-radius: 3rpx;
}

.status-tabs {
  display: flex;
  gap: 5rpx;
  background: #f8f9fa;
  border-radius: 25rpx;
  padding: 8rpx;
}

.status-tab {
  font-size: 26rpx;
  color: #6c757d;
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  transition: all 0.3s ease;
  font-weight: 500;
}

.status-tab.active {
  color: white;
  background: linear-gradient(135deg, #3498ff 0%, #3498ff 100%);
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
  transform: translateY(-2rpx);
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 25rpx;
}

.task-item {
  background: white;
  border-radius: 20rpx;
  padding: 35rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 8rpx 25rpx rgba(0, 0, 0, 0.08);
  border: 2rpx solid #f8f9fa;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.task-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 8rpx;
  background: linear-gradient(135deg, #3498ff 0%, #764ba2 100%);
}

.task-item:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
}

.task-content {
  flex: 1;
}

.task-title {
  font-size: 34rpx;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12rpx;
  display: block;
  line-height: 1.4;
}

.task-desc {
  font-size: 28rpx;
  color: #6c757d;
  margin-bottom: 20rpx;
  display: block;
  line-height: 1.5;
}

.task-meta {
  display: flex;
  gap: 35rpx;
}

.task-date, .task-author {
  font-size: 26rpx;
  color: #95a5a6;
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.task-status {
  padding: 16rpx 28rpx;
  border-radius: 25rpx;
  font-size: 26rpx;
  color: white;
  white-space: nowrap;
  font-weight: 600;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.task-status.pending {
  background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
}

.task-status.completed {
  background: linear-gradient(135deg, #4caf50 0%, #388e3c 100%);
}

/* 浮动按钮 */
.fab {
  position: fixed;
  bottom: 50rpx;
  right: 40rpx;
  width: 140rpx;
  height: 140rpx;
  background: linear-gradient(135deg, #3498ff 0%, #3498ff 100%);
  border-radius: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 12rpx 35rpx rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
  z-index: 100;
}

.fab::before {
  content: '';
  position: absolute;
  top: -4rpx;
  left: -4rpx;
  right: -4rpx;
  bottom: -4rpx;
  background: linear-gradient(135deg, #3498ff 0%, #764ba2 100%);
  border-radius: 74rpx;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

.fab:active {
  transform: scale(0.95);
  box-shadow: 0 8rpx 25rpx rgba(102, 126, 234, 0.5);
}

.fab:active::before {
  opacity: 0.3;
}

.fab-icon {
  font-size: 56rpx;
  color: white;
  font-weight: 300;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

/* 添加一些全局动画效果 */
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.fab:hover {
  animation: pulse 2s infinite;
}

/* 响应式优化 */
@media (max-width: 750rpx) {
  .task-item {
    padding: 30rpx 25rpx;
  }
  
  .modal-content {
    width: 95%;
  }
  
  .fab {
    width: 120rpx;
    height: 120rpx;
    bottom: 40rpx;
    right: 30rpx;
  }
  
  .fab-icon {
    font-size: 48rpx;
  }
}
</style>

